package net.p2pcdn.core.order.service;

import net.p2pcdn.core.order.domain.Contract;
import net.p2pcdn.core.order.domain.Order;
import net.p2pcdn.core.order.domain.OrderDetail;
import net.p2pcdn.core.order.repository.OrderDetailRepository;
import net.p2pcdn.core.order.repository.OrderRepository;
import net.p2pcdn.core.product.domain.Product;
import net.p2pcdn.core.product.domain.ProductType;
import net.p2pcdn.core.product.service.ProductService;
import net.p2pcdn.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author zx
 */
@Service
public class TrafficBagOrderHandler implements OrderHandler {
    @Autowired
    private OrderHandlerFactory orderHandlerFactory;
    @Resource
    private OrderRepository orderRepository;
    @Resource
    private OrderDetailRepository orderDetailRepository;
    @Autowired
    private UserService userService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ContractService contractService;


    @Override
    public ProductType supportType() {
        return ProductType.BAG;
    }

    @Override
    public void handle(OrderDetail detail) {
        Order order = this.orderRepository.selectByPrimaryKey(detail.getOrderId());
        Contract contract = contractService.getById(detail.getContractId());
        if (contract.getExpireTime().compareTo(new Date()) < 0) {
            throw new RuntimeException("服务过期不能充值流量包");
        }
        Product product = productService.getProduct(detail.getItemId());
        this.contractService.chargeTraffic(order.getCreator(), contract, product,detail.getNum(),getChangeType(order.getPayType()));
    }

    @Override
    public void afterPropertiesSet() {
        this.orderHandlerFactory.addHandler(supportType(), this);
    }
}
